package com.cloud.lawcase.api.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cloud.lawcase.api.bean.ChapterBean;
import com.cloud.lawcase.api.entity.TcDicLaw;
import com.cloud.lawcase.api.entity.TcDicLawCause;
import com.cloud.lawcase.api.entity.TcDicLawGroup;
import com.cloud.lawcase.api.entity.TcDicLawItem;
import com.cloud.lawcase.api.entity.TcDicLawPublishDept;
import com.cloud.lawcase.api.entity.TcLawCauseSeq;
import com.cloud.lawcase.api.mapper.TcDicLawCauseMapper;
import com.cloud.lawcase.api.mapper.TcDicLawGroupMapper;
import com.cloud.lawcase.api.mapper.TcDicLawItemMapper;
import com.cloud.lawcase.api.mapper.TcDicLawMapper;
import com.cloud.lawcase.api.mapper.TcDicLawPublishDeptMapper;
import com.cloud.lawcase.api.mapper.TcLawCauseSeqMapper;
import com.cloud.lawcase.api.service.TempService;
import com.cloud.lawcase.common.utils.ExcelHelper;
import com.cloud.lawcase.common.utils.RedisKeyHelper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import tk.mybatis.mapper.entity.Example;

@Service
@Transactional
public class TempServiceImpl implements TempService {

	@Autowired
	private TcDicLawCauseMapper TcDicLawCauseMapper;

	@Autowired
	private TcDicLawMapper tcDicLawMapper;

	@Autowired
	private TcDicLawItemMapper tcDicLawItemMapper;

	@Autowired
	private TcLawCauseSeqMapper tcLawCauseSeqMapper;
	
	@Autowired
	private TcDicLawGroupMapper tcDicLawGroupMapper;

	@Autowired
	private TcDicLawPublishDeptMapper tcDicLawPublishDeptMapper;
	
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public void refreshCauseCode() {
		List<TcDicLawCause> causes = TcDicLawCauseMapper.selectAll();

		for (TcDicLawCause c : causes) {
			StringBuilder sb = new StringBuilder(c.getCauseCode());
			TcDicLaw law = tcDicLawMapper.selectByPrimaryKey(c.getLawId());
			sb.append(law.getLawCode().substring(2, law.getLawCode().length()));

			int excuTeType = Integer.valueOf(c.getCauseCode());
			TcLawCauseSeq pk = new TcLawCauseSeq();
			pk.setLawId(law.getLawId());
			pk.setExcuteTypeId(excuTeType);
			TcLawCauseSeq seq = tcLawCauseSeqMapper.selectByPrimaryKey(pk);
			if (null == seq) {
				seq = new TcLawCauseSeq();
				seq.setLawId(law.getLawId());
				seq.setExcuteTypeId(excuTeType);
				seq.setSeqValue(1);
				sb.append(String.format("%03d", 1));
				tcLawCauseSeqMapper.insert(seq);
			} else {
				int value = seq.getSeqValue();
				sb.append(String.format("%03d", value + 1));
				seq.setSeqValue(value + 1);
				tcLawCauseSeqMapper.updateByPrimaryKey(seq);
			}
			TcDicLawCause temp = new TcDicLawCause();
			temp.setCauseId(c.getCauseId());
			temp.setCauseCode(sb.toString());
			TcDicLawCauseMapper.updateByPrimaryKeySelective(temp);
		}
	}

	@Override
	public void test() {
		Page<Map<String, Object>> page = PageHelper.startPage(1, 2)
				.doSelectPage(() -> TcDicLawCauseMapper.selectByDynamicSQL(
						"select * from tc_dic_law_group t1, tc_dic_law t2 where t1.group_id = t2.group_id and t1.group_id = 2"));
		System.out.println(page.getTotal());
	}

	@Override
	public void loadData() {
		// 装载数据
		InputStream in;
		try {
			in = new FileInputStream(new File("F:\\法规章节.xlsx"));
			List<ChapterBean> chapters = ExcelHelper.xlsx2List(in, new String[] { "lawTitle", "lawCode", "chapterId",
					"chapterName", "sectionId", "sectionName", "startArticleId", "endArticleId" }, ChapterBean.class);
			for (ChapterBean chapter : chapters) {
				Example example = new Example(TcDicLaw.class);
				Example.Criteria criteria = example.createCriteria();
				criteria.andEqualTo("lawTitle", chapter.getLawTitle());
				List<TcDicLaw> law = tcDicLawMapper.selectByExample(example);
				if (null != law && law.size() == 1) {
					TcDicLaw dicLaw = law.get(0);
					// 章
					Example chapterExample = new Example(TcDicLawItem.class);
					Example.Criteria chapterCriteria = chapterExample.createCriteria();
					chapterCriteria.andEqualTo("chapterId", chapter.getChapterId());
					chapterCriteria.andEqualTo("sectionId", 0);
					chapterCriteria.andEqualTo("articleId", 0);
					chapterCriteria.andEqualTo("lawId", dicLaw.getLawId());
					List<TcDicLawItem> chapterItems = tcDicLawItemMapper.selectByExample(chapterExample);
					if (null == chapterItems || chapterItems.size() == 0) {
						TcDicLawItem item = new TcDicLawItem();
						item.setItemId(RedisKeyHelper.genereateKey(TcDicLawItem.class));
						item.setLawId(dicLaw.getLawId());
						item.setChapterId(chapter.getChapterId());
						item.setSectionId(0);
						item.setArticleId(0);
						item.setParagraphId(0);
						item.setSubParagraphId(0);
						item.setEntryId(0);
						item.setItemTypeId(1);
						item.setItemContent(chapter.getChapterName());
						item.setItemCode(dicLaw.getLawCode() + String.format("%02d", item.getChapterId())
								+ String.format("%02d", item.getSectionId())
								+ String.format("%03d", item.getArticleId())
								+ String.format("%02d", item.getParagraphId())
								+ String.format("%02d", item.getSubParagraphId())
								+ String.format("%02d", item.getEntryId()));
						tcDicLawItemMapper.insert(item);
					}
					// 节chapterItem
					if (chapter.getSectionId() > 0) {
						Example sectionExample = new Example(TcDicLawItem.class);
						Example.Criteria sectionCriteria = sectionExample.createCriteria();
						sectionCriteria.andEqualTo("chapterId", chapter.getChapterId());
						sectionCriteria.andEqualTo("sectionId", chapter.getSectionId());
						sectionCriteria.andEqualTo("articleId", 0);
						sectionCriteria.andEqualTo("lawId", dicLaw.getLawId());
						List<TcDicLawItem> sectionItems = tcDicLawItemMapper.selectByExample(sectionExample);
						if (null == sectionItems || sectionItems.size() == 0) {
							TcDicLawItem item = new TcDicLawItem();
							item.setItemId(RedisKeyHelper.genereateKey(TcDicLawItem.class));
							item.setLawId(dicLaw.getLawId());
							item.setChapterId(chapter.getChapterId());
							item.setSectionId(chapter.getSectionId());
							item.setArticleId(0);
							item.setParagraphId(0);
							item.setSubParagraphId(0);
							item.setEntryId(0);
							item.setItemTypeId(2);
							item.setItemContent(chapter.getSectionName());
							item.setItemCode(dicLaw.getLawCode() + String.format("%02d", item.getChapterId())
									+ String.format("%02d", item.getSectionId())
									+ String.format("%03d", item.getArticleId())
									+ String.format("%02d", item.getParagraphId())
									+ String.format("%02d", item.getSubParagraphId())
									+ String.format("%02d", item.getEntryId()));
							tcDicLawItemMapper.insert(item);
						}
					}
					// 更新条目章节信息
					jdbcTemplate.update(
							"update tc_dic_law_item set chapter_id = ? , section_id = ? where law_id = ? and article_id >= ? and article_id <= ?",
							chapter.getChapterId(), chapter.getSectionId(), dicLaw.getLawId(),
							chapter.getStartArticleId(), chapter.getEndArticleId());

				}
			}
			jdbcTemplate.update(
					"update tc_dic_law_item t1, tc_dic_law t2 set t1.item_code = concat(t2.law_code, lpad(t1.chapter_id, 2,'0'), lpad(t1.section_id, 2,'0'), lpad(t1.article_id, 2,'0'), lpad(t1.paragraph_id, 2,'0'), lpad(t1.sub_paragraph_id, 2,'0'),lpad(t1.entry_id, 2,'0')) where t1.law_id = t2.law_id;");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void flushDic() {
		Example groupExample = new Example(TcDicLawGroup.class);
		Example.Criteria groupCriteria = groupExample.createCriteria();
		groupCriteria.andEqualTo("seniorGroupId", 382);
		List<TcDicLawGroup> groups = tcDicLawGroupMapper.selectByExample(groupExample);
		Integer maxId = jdbcTemplate.queryForObject("select max(dept_id) + 1 from tc_dic_law_publish_dept", Integer.class);
		for(TcDicLawGroup grp : groups){
			String groupName = grp.getGroupName().replaceAll("(\\(.*?\\))", "");
			if(!groupName.equals("河北省") && !groupName.equals("天津市") &&
					!groupName.equals("宁夏回族自治区")){
				int deptId = maxId++;
				TcDicLawPublishDept dept = new TcDicLawPublishDept();
				dept.setDeptId(deptId);
				dept.setSeniorId(0);
				dept.setDeptName(groupName);
				dept.setDeptCode("/"+deptId+"/");
				dept.setEnableFlag(1);
				dept.setDisplayOrder(deptId);
				tcDicLawPublishDeptMapper.insert(dept);
				
				//人民代表大会
				int deptId1 = maxId++;
				TcDicLawPublishDept dept1 = new TcDicLawPublishDept();
				dept1.setDeptId(deptId1);
				dept1.setSeniorId(deptId);
				dept1.setDeptName(groupName + "人民代表大会");
				dept1.setDeptCode("/"+deptId+"/"+deptId1+"/");
				dept1.setEnableFlag(1);
				dept1.setDisplayOrder(deptId1);
				tcDicLawPublishDeptMapper.insert(dept1);
				
				//人大常委会
				int deptId2 = maxId++;
				TcDicLawPublishDept dept2 = new TcDicLawPublishDept();
				dept2.setDeptId(deptId2);
				dept2.setDeptName(groupName + "人大常委会");
				dept2.setSeniorId(deptId);
				dept2.setDeptCode("/"+deptId+"/"+deptId2+"/");
				dept2.setEnableFlag(1);
				dept2.setDisplayOrder(deptId2);
				tcDicLawPublishDeptMapper.insert(dept2);
				
				//政府
				int deptId3 = maxId++;
				TcDicLawPublishDept dept3 = new TcDicLawPublishDept();
				dept3.setDeptId(deptId3);
				dept3.setSeniorId(deptId);
				dept3.setDeptName(groupName + "政府");
				dept3.setDeptCode("/"+deptId+"/"+ deptId3 +"/");
				dept3.setEnableFlag(1);
				dept3.setDisplayOrder(deptId3);
				tcDicLawPublishDeptMapper.insert(dept3);
			}
		}
		
	}

}
